<?php

use Phalcon\Cli\Task;
use PLibrary\TConfig;
use Phalcon\Logger\Adapter\File as FileAdapter;
use Phalcon\Db\Adapter\Pdo\Mysql;
/**
 * 异步毫秒定时任务
 * @author dem
 * 注： 定时任务请按照标准编写, 函数修饰符必须为private ,命名以do开头
 * 注释请按照 demo 格式 
 * 定时任务支持毫秒级别，具体查看https://wiki.swoole.com/wiki/page/244.html
 *
 */
//

//class CrontabTask extends Task
class CrontabTask extends Task
{

    /***计划任务入口***/
    function startAction($param){
        if(empty($param))
        {
            $this->writetotable('crontab parameter error', '');
        }else {
            $than = $this;
            try {
                $classMethods = get_class_methods($this);
                if (in_array($param[0], $classMethods)) {
                    call_user_func(array($than, $param[0]));
                    $than->contabLog(date('YmdHis') . '| Task |' . $param[0]);
                } else {
                    $this->writetotable("crontab not found function " . $param[0], '');
                }
            } catch (Exception $e) {
                $this->writetotable($e, '');

            }
        }
    } 

    
    /**
     * 记录定时任务执行日志
     * @param unknown $msg
     * @return \Phalcon\Logger\Adapter
     */
    private function contabLog($msg){
        $logfile = TConfig::instance()->get('crontabLog').'/'.date('Y-m').'/';
        if(!file_exists($logfile)){
            mkdir($logfile);
        }
        $logfile.=date('Ymd').'.log';
        $logger = new FileAdapter($logfile);
        return $logger->log($msg);
        
    }

    private function test()
    {
        //echo 123456;
        $task='cd F:/work/&java HelloWorld';
        exec($task,$output, $return_var);
        $this->writetotable(json_encode($output),$task);
        file_put_contents("E:/log/error999.log",json_encode($output));

    }

    private function test1()
    {
        //echo 123456;$
        $task='cd F:/back/php-crontab-master/&php demo888.php';
        exec($task, $output, $return_var);
        $this->writetotable(json_encode($output),$task);
        file_put_contents("E:/log/error999.log",json_encode($output));

    }

    private function writetotable($msg,$task)
    {
        $pdo=new Mysql(array(
            "host" => "localhost",
            "username" => "root",
            "password" => "855447",
            "dbname" => "test"
        ));
        $query = "insert into msg_info set msg=:msg,task=:task,create_time=:create_time";
        $result = $pdo->prepare($query);
        $result->execute(array(':msg'=>$msg,':task'=>$task,':create_time'=>time()));
    }

}